//
//  PhotoBrowserViewController.swift
//  LBWeibo
//
//  Created by 李博 on 15/7/4.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD


///可重用标示符
private let LBPhotoBrowserCellReuseIdentifier = "LBPhotoBrowserCellReuseIdentifier"

class PhotoBrowserViewController: UIViewController,UICollectionViewDataSource,PhotoBrowserViewCellDelegate {
    ///图像数组
    private var imageURLs: [NSURL]
    ///用户选择图片索引
    private var selectedIndex: Int
    
    override func viewDidLayoutSubviews() {
        prepareLayout()
        
        //跳转用户指定界面
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    private func prepareLayout() {

        layout.itemSize = collectionView.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
    }
    
    init(urls: [NSURL],index: Int) {
        imageURLs = urls
        selectedIndex = index
        
        super.init(nibName: nil, bundle: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        
        //将视图的宽调的20
        var screenBounds = UIScreen.mainScreen().bounds
        screenBounds.size.width += 20
        view = UIView(frame: screenBounds)
        
        view.backgroundColor = UIColor.blackColor()
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        collectionView.ff_Fill(view)
        saveButton.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))
        closeButton.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        prepareCollectionView()
        
    }
    private func prepareCollectionView() {
    
        collectionView.backgroundColor = UIColor.clearColor()
        collectionView.dataSource = self
        //collectionView.delegate = self
        
        collectionView.registerClass(PhotoBrowserViewCell.self, forCellWithReuseIdentifier: LBPhotoBrowserCellReuseIdentifier)
    }
    
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func save() {
        
        let image = currentImageView().image!
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
    }
    
    ///  返回当前显示图片的索引
    func currentImageIndex() -> Int {
        return collectionView.indexPathsForVisibleItems().last!.item
    }

    
    ///  获得当前显示的 图像视图
    func currentImageView() -> UIImageView {
        // 0. 拿到当前的cell
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PhotoBrowserViewCell
        
        // 1. 拿到图像
        return cell.imageView
    }
    
    
    
    //- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            SVProgressHUD.showInfoWithStatus("保存失败")
        } else {
            SVProgressHUD.showInfoWithStatus("保存成功")
        }

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
    //MARK: -- collection 数据源 --
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LBPhotoBrowserCellReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowserViewCell
        cell.backgroundColor = UIColor.clearColor()
        cell.imageURL = imageURLs[indexPath.item]
        
        cell.photoDelegate = self
        
        return cell

    }
    
    func photoViewCellDidTapImage() {
        //关闭界面
        close()
    }
    
    func photoViewDidZooming(scale: CGFloat) {
        
        photoScale = scale
        //隐藏控件
        hiddenControl(photoScale < 1.0)
        
        //交互式转场
        if photoScale < 1.0 {
            startInteractiveTransition(self)
        }else {
            //恢复形变
            view.transform = CGAffineTransformIdentity
            view.alpha = 1.0
        }
        
    }
    
    func photoViewDidEndZoom() {
        if photoScale < 0.8 {
            completeTransition(true)
        }
    }
    
    ///隐藏控件
    private func hiddenControl(isHidden: Bool) {
        view.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
        saveButton.hidden = isHidden
        closeButton.hidden = isHidden
    }

    //MARK: -- 控件懒加载 --

    lazy private var layout = UICollectionViewFlowLayout()
    lazy private var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    lazy private var saveButton: UIButton = UIButton(title: "保存", fontSize: 14)
    lazy private var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14)

    //照片的缩放比例
    private var photoScale: CGFloat = 0
}

extension PhotoBrowserViewController: UIViewControllerInteractiveTransitioning, UIViewControllerContextTransitioning {
    
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        //缩放视图
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        //设置透明度
        view.alpha = photoScale
    }
    
    func completeTransition(didComplete: Bool) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func containerView() -> UIView? { return self.view.superview }
    func isAnimated() -> Bool { return true }
    func isInteractive() -> Bool { return true }
    func transitionWasCancelled() -> Bool { return true }
    func presentationStyle() -> UIModalPresentationStyle { return UIModalPresentationStyle.Custom }
    func updateInteractiveTransition(percentComplete: CGFloat) {}
    func finishInteractiveTransition() {}
    func cancelInteractiveTransition() {}
    
    func viewControllerForKey(key: String) -> UIViewController? { return self }
    func viewForKey(key: String) -> UIView? { return self.view }
    func targetTransform() -> CGAffineTransform { return CGAffineTransformIdentity }
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
    func finalFrameForViewController(vc: UIViewController) -> CGRect { return CGRectZero }
}

